<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 左侧欢迎区域 -->
      <div class="welcome-section">
        <div class="welcome-content">
          <h1 class="welcome-title">欢迎来到</h1>
          <h2 class="platform-name">校园服务平台</h2>
          <p class="welcome-text">连接校园，服务师生</p>
          <div class="feature-list">
            <div class="feature-item">
              <el-icon><Calendar /></el-icon>
              <span>活动发布与报名</span>
            </div>
            <div class="feature-item">
              <el-icon><Search /></el-icon>
              <span>失物招领</span>
            </div>
            <div class="feature-item">
              <el-icon><User /></el-icon>
              <span>个人中心</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="form-section">
        <div class="form-wrapper">
          <!-- 切换标签 -->
          <div class="form-tabs">
            <div
              class="tab-item"
              :class="{ active: isLogin }"
              @click="switchToLogin"
            >
              登录
            </div>
            <div
              class="tab-item"
              :class="{ active: !isLogin }"
              @click="switchToRegister"
            >
              注册
            </div>
          </div>

          <!-- 登录表单 -->
          <el-form
            v-show="isLogin"
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            @keyup.enter="handleLogin"
          >
            <h3 class="form-title">账号登录</h3>

            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <div class="form-options">
                <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
                <el-link type="primary" :underline="false">忘记密码?</el-link>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                @click="handleLogin"
                class="submit-btn"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 注册表单 -->
          <el-form
            v-show="!isLogin"
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
            @keyup.enter="handleRegister"
          >
            <h3 class="form-title">创建账号</h3>

            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                size="large"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="loading"
                @click="handleRegister"
                class="submit-btn"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Calendar, Search } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import useUserStore from '@/stores/modules/user'
import { reqRegister } from '@/api/user'
import type { loginFormData, registerFormData } from '@/api/user/type'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 表单切换
const isLogin = ref(true)
const loading = ref(false)

// 表单引用
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

// 登录表单数据
const loginForm = reactive<loginFormData>({
  username: '',
  password: '',
  rememberMe: false
})

// 页面加载时恢复记住的用户信息
onMounted(() => {
  const savedUsername = localStorage.getItem('rememberUsername')
  const rememberMe = localStorage.getItem('rememberMe') === 'true'

  if (rememberMe && savedUsername) {
    loginForm.username = savedUsername
    loginForm.rememberMe = true
  }
})

// 注册表单数据
const registerForm = reactive<registerFormData>({
  username: '',
  password: '',
  confirmPassword: ''
})

// 登录表单验证规则
const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ]
})

// 确认密码验证
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 注册表单验证规则
const registerRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

// 切换到登录
const switchToLogin = () => {
  isLogin.value = true
  // 重置注册表单
  registerFormRef.value?.resetFields()
}

// 切换到注册
const switchToRegister = () => {
  isLogin.value = false
  // 重置登录表单
  loginFormRef.value?.resetFields()
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.userLogin(loginForm)
        // 获取用户信息
        await userStore.userInfo()

        // 处理"记住我"功能（出于安全考虑，只保存用户名）
        if (loginForm.rememberMe) {
          localStorage.setItem('rememberUsername', loginForm.username)
          localStorage.setItem('rememberMe', 'true')
        } else {
          // 清除保存的信息
          localStorage.removeItem('rememberUsername')
          localStorage.removeItem('rememberMe')
        }

        ElMessage.success('登录成功')

        // 跳转到首页或重定向页面
        const redirect = route.query.redirect as string
        router.push(redirect || '/home')
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await reqRegister(registerForm)

        if (result.code === 200) {
          ElMessage.success('注册成功，请登录')
          // 切换到登录表单，并填充用户名
          isLogin.value = true
          loginForm.username = registerForm.username
          loginForm.password = ''
          // 重置注册表单
          registerFormRef.value?.resetFields()
        } else {
          ElMessage.error(result.message || '注册失败')
        }
      } catch (error: any) {
        ElMessage.error(error.message || '注册失败')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('/login_background.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.4);
  }
}

.login-box {
  position: relative;
  z-index: 1;
  display: flex;
  width: 900px;
  height: 550px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.welcome-section {
  flex: 1;
  background: linear-gradient(135deg, #9266ea 0%, #4ba295 100%);
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: white;
}

.welcome-content {
  .welcome-title {
    font-size: 24px;
    font-weight: 300;
    margin-bottom: 10px;
  }

  .platform-name {
    font-size: 36px;
    font-weight: 600;
    margin-bottom: 20px;
  }

  .welcome-text {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 40px;
  }
}

.feature-list {
  .feature-item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;
    font-size: 15px;

    .el-icon {
      font-size: 20px;
      opacity: 0.9;
    }
  }
}

.form-section {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.form-wrapper {
  width: 100%;
  max-width: 360px;
  margin: 0 auto;
}

.form-tabs {
  display: flex;
  margin-bottom: 30px;
  border-bottom: 2px solid #f0f0f0;
}

.tab-item {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #999;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;

  &.active {
    color: #66d2ea;

    &::after {
      content: '';
      position: absolute;
      bottom: -2px;
      left: 0;
      right: 0;
      height: 2px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
  }

  &:hover {
    color: #667eea;
  }
}

.form-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

.login-form,
.register-form {
  :deep(.el-form-item) {
    margin-bottom: 24px;
  }

  :deep(.el-input__wrapper) {
    padding: 12px 15px;
    border-radius: 8px;
  }

  :deep(.el-input__prefix) {
    color: #999;
  }
}

.form-options {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-box {
    flex-direction: column;
    width: 90%;
    height: auto;
    max-height: 90vh;
  }

  .welcome-section {
    padding: 30px 20px;

    .welcome-title {
      font-size: 20px;
    }

    .platform-name {
      font-size: 28px;
    }
  }

  .feature-list {
    display: none;
  }

  .form-section {
    padding: 30px 20px;
  }
}
</style>
